# Copyright (c) 2020 Presto Labs Pte. Ltd.
# Author: xguo, donggu

import requests
from coin2.exchange.product_info import ProductInfoDefault
from coin2.exchange.symbology import SymbologyInfo


def gen_var_ticks(quote):
  # retrieved from https://id.upbit.com/service_center/guide
  price_list = [1e9, 20000000., 10000000., 5000000., 1000000., 100000., 10000., 1000., 100., 10., 1., 0]
  tick_list = [10000., 5000., 1000., 500., 100., 50., 10., 1., 0.1, 0.01, 0.001]
  result = []
  if quote == "USDT":
    result.append([0, 1e9, 0.001])
  elif quote == "BTC":
    result.append([0, 1e9, 0.00000001])
  elif quote == "IDR":
    range_list = list(zip(price_list[:-1], price_list[1:]))
    for r, tick in zip(range_list, tick_list):
      assert r[0] > r[1]
      info = {
          'from': r[1],
          'to': r[0],
          'value': tick,
      }
      result.append([info['from'], info['to'], info['value']])
  return result


def gen_min_amount(quote):
  # retrieved from https://id.upbit.com/service_center/guide
  if quote == "USDT":
    return float(0.0005)
  elif quote == "BTC":
    return float(0.0005)
  elif quote == "IDR":
    return float(5000)
  else:
    print(quote)
    raise ValueError("unsupported quote %s" % quote)


def generate():
  mea = 'Spot.Upbitid.v1'
  me = 'Spot.Upbitid'
  default = ProductInfoDefault()
  symbol_info = SymbologyInfo()
  data = requests.get('https://id-api.upbit.com/v1/market/all?isDetails=false').json()

  pis = []
  for info in data:
    native_symbol = info['market']
    native_quote, native_base = native_symbol.split('-')
    base = symbol_info.native_to_norm_currency(mea, native_base)
    quote = symbol_info.native_to_norm_currency(mea, native_quote)
    symbol = "%s-%s" % (base, quote)

    pi = dict(
        symbol=symbol,
        base=base,
        quote=quote,
        native_symbol=native_symbol,
        native_base=native_base,
        native_quote=native_quote,
        is_inverse=False,
        price_ticksize=gen_var_ticks(quote),
        qty_ticksize=0.0001,
        min_amount=gen_min_amount(quote),
    )

    pi = {**pi, **default.product_info(me, symbol)}
    pis.append(pi)

  pis = sorted(pis, key=lambda x: x['symbol'])
  return pis


def gen_coin1_constants():
  data = generate()
  coin_list = [info['native_base'] for info in data]
  return {
      'coin_list': coin_list
  }


if __name__ == '__main__':
  import json
  config = generate()
  print(json.dumps(config, indent=2))
